﻿/**
 *    Copyright 2012 Yohan Courbe
 *
 *  Licensed under the Apache License, Version 2.0 (the "License 
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *  
 *      http://www.apache.org/licenses/LICENSE-2.0
 *      
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */

using System.Net;
using PacketDotNet;

namespace NetworkAnalyzer.Engines.Statistics
{
    public class StatisticsSummary
    {
        public IPAddress Localhost { get; private set; }

        public readonly ProtocolUsageList ProtocolUsages;

        public StatisticsSummary(IPAddress localHost)
        {
            Localhost = localHost;

            ProtocolUsages = new ProtocolUsageList();
        }

        public bool Match(IPAddress localhost)
        {
            return IPAddress.Equals(localhost, Localhost);
        }

        public void AddTcpPacket(IpPacket ipPacket, TcpPacket tcpPacket, uint packetSize)
        {
            var applicativeProtocol = Tools.GetApplicativeProtocolByPort(tcpPacket.SourcePort, tcpPacket.DestinationPort);

            if (Tools.IsLocalHost(ipPacket.SourceAddress))
            {
                ProtocolUsages.GetProtocolUsage(ipPacket.DestinationAddress, tcpPacket.DestinationPort, IPProtocolType.TCP, applicativeProtocol).UploadBandwidth += packetSize;
            }
            else
            {
                ProtocolUsages.GetProtocolUsage(ipPacket.SourceAddress, tcpPacket.SourcePort, IPProtocolType.TCP, applicativeProtocol).DownloadBandwidth += packetSize;   
            }
        }

        public void AddUdpPacket(IpPacket ipPacket, UdpPacket udpPacket, uint packetSize)
        {
            var applicativeProtocol = Tools.GetApplicativeProtocolByPort(udpPacket.SourcePort, udpPacket.DestinationPort);

            if (Tools.IsLocalHost(ipPacket.SourceAddress))
            {
                ProtocolUsages.GetProtocolUsage(ipPacket.DestinationAddress, udpPacket.DestinationPort, IPProtocolType.UDP, applicativeProtocol).UploadBandwidth += packetSize;
            }
            else
            {
                ProtocolUsages.GetProtocolUsage(ipPacket.SourceAddress, udpPacket.SourcePort, IPProtocolType.UDP, applicativeProtocol).DownloadBandwidth += packetSize;
            }
        }

        public void AddOtherPacket(Packet packet)
        {
            
        }
    }
}
